package com.wannengbang.cloudleader.homepage;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.ActivateResultBean;
import com.wannengbang.cloudleader.bean.BaseResponseBean;
import com.wannengbang.cloudleader.bean.MachinesInfoBean;
import com.wannengbang.cloudleader.bean.ScanActivateBean;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.utils.DateTimeUtil;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.CommonNoTitleDialog;
import com.wannengbang.cloudleader.widget.ViewLoading;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MachinesInfoActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_order_fee)
    TextView tvOrderFee;
    @BindView(R.id.tv_agent_name)
    TextView tvAgentName;
    @BindView(R.id.tv_current_status)
    TextView tvCurrentStatus;
    @BindView(R.id.tv_jihuo_status)
    TextView tvJihuoStatus;
    @BindView(R.id.tv_order_bonuses_one_grant_status)
    TextView tvOrderBonusesOneGrantStatus;
    @BindView(R.id.tv_order_bonuses_two_grant_status)
    TextView tvOrderBonusesTwoGrantStatus;
    @BindView(R.id.tv_target_bonuses_grant_status)
    TextView tvTargetBonusesGrantStatus;
    @BindView(R.id.tv_hight_value)
    TextView tvHightValue;
    @BindView(R.id.tv_common_value)
    TextView tvCommonValue;
    @BindView(R.id.tv_wxpay_alipay_value)
    TextView tvWxpayAlipayValue;
    @BindView(R.id.tv_copy)
    TextView tvCopy;
    @BindView(R.id.tv_jiju_type)
    TextView tvJijuType;
    @BindView(R.id.tv_use_agent_name)
    TextView tvUseAgentName;
    @BindView(R.id.tv_enable_up_date)
    TextView tvEnableUpDate;
    @BindView(R.id.ll_enable_up_date)
    LinearLayout llEnableUpDate;
    @BindView(R.id.tv_mem_name)
    TextView tvMemName;
    @BindView(R.id.tv_mem_no)
    TextView tvMemNo;
    @BindView(R.id.tv_mem_phone)
    TextView tvMemPhone;
    @BindView(R.id.tv_bind_mem_time)
    TextView tvBindMemTime;
    @BindView(R.id.ll_mem_info)
    LinearLayout llMemInfo;
    @BindView(R.id.tv_compre_value)
    TextView tvCompreValue;
    @BindView(R.id.tv_rate_type)
    TextView tvRateType;
    @BindView(R.id.tv_is_vip)
    TextView tvIsVip;
    private String id;
    private IHomePageModel homePageModel = new HomePageModelImpl();
    private MachinesInfoBean.DataBean dataBean;
    private String order_no;
    private Handler mHandler = new Handler(Looper.getMainLooper());

    private Runnable mTimeCounterRunnable = new Runnable() {
        @Override
        public void run() {
            requestReturncashOrderShow();
        }
    };
    private CommonNoTitleDialog.Builder dialogBuild;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_machines_info);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    public void initView() {
        id = getIntent().getStringExtra("id");
    }

    public void initData() {
        homePageModel.requestDeviceUnifyShow(id, new DataCallBack<MachinesInfoBean>() {
            @Override
            public void onSuccessful(MachinesInfoBean bean) {
                dataBean = bean.getData();
                tvNumber.setText(dataBean.getNo());
                String money = NumberFormatUtils.formatTwoDecimal(Double.parseDouble(dataBean.getStore_order_fee()) / 100);
                tvOrderFee.setText(money + "元");
                tvAgentName.setText(dataBean.getBind_agent_name());
                if (dataBean.getUse_status() == 0) {
                    tvCurrentStatus.setText("未使用");
                } else if (dataBean.getUse_status() == 1) {
                    tvCurrentStatus.setText("已使用");
                } else if (dataBean.getUse_status() == 2) {
                    tvCurrentStatus.setText("已禁用");
                }
                tvJihuoStatus.setText(dataBean.getEnable_status() == 0 ? "未激活" : "已激活");
                tvOrderBonusesOneGrantStatus.setText(dataBean.getOrder_bonuses_one_grant_status() == 0 ? "未完成" : "已完成");
                tvOrderBonusesTwoGrantStatus.setText(dataBean.getOrder_bonuses_two_grant_status() == 0 ? "未完成" : "已完成");
                if (dataBean.getTarget_bonuses_grant_status() == 1) {
                    tvTargetBonusesGrantStatus.setText("已完成");
                } else {
                    tvTargetBonusesGrantStatus.setText("未完成");
                }
                tvCompreValue.setText(dataBean.getCompre_rate() + "%");
                tvHightValue.setText(dataBean.getHigh_rate() + "%");
                tvCommonValue.setText(dataBean.getNormal_rate() + "%");
                tvWxpayAlipayValue.setText(dataBean.getLow_rate() + "%");

                if (dataBean.getRate_type() == 4) {
                    tvRateType.setText("综合类");
                } else {
                    tvRateType.setText("高端类");
                }

                if (dataBean.getIs_send() == 0) {
                    if (dataBean.getType() == 1) {
                        tvJijuType.setText("采购的云小宝");
                    } else if (dataBean.getType() == 2) {
                        tvJijuType.setText("采购的云商宝");
                    } else if (dataBean.getType() == 3) {
                        tvJijuType.setText("采购的云小宝");
                    } else if (dataBean.getType() == 4) {
                        tvJijuType.setText("采购的云小宝");
                    }
                } else {
                    tvJijuType.setText("兑换的云小宝");
                }
                tvUseAgentName.setText(dataBean.getUse_agent());

                if (TextUtils.isEmpty(dataBean.getEnable_up_date())) {
                    llEnableUpDate.setVisibility(View.GONE);
                } else {
                    llEnableUpDate.setVisibility(View.VISIBLE);
                    tvEnableUpDate.setText(dataBean.getEnable_up_date());
                }
                //已激活
                if (dataBean.getEnable_status() == 1) {
                    llMemInfo.setVisibility(View.VISIBLE);
                    tvMemNo.setText(dataBean.getMem_no());

                    if (!TextUtils.isEmpty(dataBean.getMem_name())) {
                        String name = dataBean.getMem_name().substring(0, dataBean.getMem_name().length() - 1) + "*";
                        tvMemName.setText(name);
                    } else {
                        tvMemName.setText("");
                    }

                    tvMemPhone.setText(dataBean.getMem_phone());
                    if (TextUtils.isEmpty(dataBean.getEnable_time()) || "0".equals(dataBean.getEnable_time())) {
                        tvBindMemTime.setText("");
                    } else {
                        tvBindMemTime.setText(DateTimeUtil.format7(new Date(Long.parseLong(dataBean.getEnable_time()) * 1000)));
                    }
                } else {
                    llMemInfo.setVisibility(View.GONE);
                }
                if (dataBean.getType() == 1) {
                    tvIsVip.setText("云小宝");
                } else if (dataBean.getType() == 2) {
                    tvIsVip.setText("云商宝");
                } else if (dataBean.getType() == 3) {
                    tvIsVip.setText("云小宝Vip版");
                } else if (dataBean.getType() == 4) {
                    tvIsVip.setText("云小宝Plus版");
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private Dialog progress;

    public void showProgress(String message) {
        if (progress == null) {
            progress = new Dialog(mActivity, R.style.ShowProgressUtils);
        }
        View view = View.inflate(mActivity, R.layout.dialog_view_loading, null);
        TextView textView = view.findViewById(R.id.loadingText);
        textView.setText(message);
        progress.setContentView(view);
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(true);
        try {
            progress.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissProgress() {
        if (progress == null) {
            return;
        }
        try {
            progress.dismiss();
            progress = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void requestTestCloudHorn() {
        if (dataBean == null) {
            return;
        }
        ViewLoading.showProgress(mActivity, "推送中......");
        homePageModel.requestTestCloudHorn(dataBean.getNo(), new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort(bean.getMsg());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    /**
     * 设备激活
     *
     * @param code
     */
    public void requestDeviceEnable(String code) {
        if (dataBean == null) {
            return;
        }
        if (!NumberFormatUtils.isNumeric(code)) {
            ToastUtil.showShort("请扫描付款码");
            return;
        }
        showProgress("激活中.....");
        homePageModel.requestDeviceEnable(id, dataBean.getNo(), code, "", new DataCallBack<ScanActivateBean>() {
            @Override
            public void onSuccessful(ScanActivateBean bean) {
                order_no = bean.getData().getOrder_no();
                requestReturncashOrderShow();
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    public void requestReturncashOrderShow() {
        homePageModel.requestReturncashOrderShow(order_no, new DataCallBack<ActivateResultBean>() {
            @Override
            public void onSuccessful(ActivateResultBean bean) {
                if (bean.getData().getPay_status() == 1) {
                    dismissProgress();
                    ToastUtil.showShort("激活成功");
                    initData();
                    mHandler.removeCallbacks(mTimeCounterRunnable);
                } else {
                    mHandler.postDelayed(mTimeCounterRunnable, 1 * 1000);
                }
                Log.d("--------", "" + order_no);
            }

            @Override
            public void onFailed(String msg, String code) {
                dismissProgress();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭定时任务
        mHandler.removeCallbacks(mTimeCounterRunnable);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫描取消", Toast.LENGTH_LONG).show();
            } else {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
                String code = scanResult.getContents();
                requestDeviceEnable(code);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick(R.id.tv_copy)
    public void onViewClicked() {
        if (dataBean == null) {
            return;
        }
        //获取剪贴板管理器
        ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", dataBean.getNo());
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
        ToastUtil.showShort("复制成功");
    }
}
